package it.localhost.deepthought.one.common;

import it.localhost.deepthought.one.R;
import it.localhost.deepthought.one.fragment.ProgressDialogFragment;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.ZipInputStream;

import android.app.Activity;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {
	public static final int POSSIBLE_STATES = 258250;
	private static final String SELECTION = "input = ? AND player = ?";
	private static final String AI_ASSET = "ai.sql.zip";
	private static final String DATABASE_NAME = "youlose.db";
	private static final String TABLE_NAME = "youLose";
	private static final String[] COLUMNS = new String[] { "sxpos", "dxpos" };
	private static final String ONE = "1";
	private static final String ZERO = "0";
	private Activity context;

	public DatabaseHelper(Activity context) {
		super(context, DATABASE_NAME, null, 1);
		this.context = context;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		ProgressDialogFragment pdf = new ProgressDialogFragment();
		try {
			pdf.show(context, R.string.creatingDB, POSSIBLE_STATES + 4, ProgressDialog.STYLE_HORIZONTAL);
			ZipInputStream zis = new ZipInputStream(context.getAssets().open(AI_ASSET));
			if (zis.getNextEntry() != null) {
				InputStreamReader isr = new InputStreamReader(zis);
				BufferedReader reader = new BufferedReader(isr);
				String thisLine;
				int count = 0;
				while ((thisLine = reader.readLine()) != null) {
					db.execSQL(thisLine);
					pdf.setProgress(++count);
				}
				reader.close();
				isr.close();
			}
			zis.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			pdf.dismiss();
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	}

	/**
	 * 
	 * @param input
	 *           String turno corrente
	 * @param aiOdd
	 *           true AI dispari, false AI pari
	 * @return sxPos, dxPos: posizione 0-based dei 2 elementi da spostare
	 */
	public Cursor getMoves(String input, boolean aiOdd) {
		return getReadableDatabase().query(TABLE_NAME, COLUMNS, SELECTION, new String[] { input, aiOdd ? ONE : ZERO }, null, null, null);
	}

	public boolean checkDB() {
		SQLiteDatabase rdb = getReadableDatabase();
		ProgressDialogFragment pdf = new ProgressDialogFragment();
		pdf.show(context, R.string.checkDB, 0, ProgressDialog.STYLE_SPINNER);
		boolean out;
		if (out = rdb.query(TABLE_NAME, null, null, null, null, null, null).getCount() != POSSIBLE_STATES)
			context.deleteDatabase(DATABASE_NAME);
		pdf.dismiss();
		return !out;
	}
}